package com.sunwayhorizo.health.business.clinic.emr.template;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.ejb.Stateless;

import org.jboss.seam.Component;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Transactional;

import com.sunwayhorizo.health.business.base.BaseManager;
import com.sunwayhorizo.health.business.clinic.emr.template.query.TemplateQueryLocal;
import com.sunwayhorizo.health.business.dto.ResultsDTO;
import com.sunwayhorizo.health.business.dto.clinic.emr.template.TemplateDTO;
import com.sunwayhorizo.health.business.dto.patad.empi.PatientBaseInfoDTO;
import com.sunwayhorizo.health.business.dto.registries.DepartmentDTO;
import com.sunwayhorizo.health.business.registries.employee.EmployeeManagerLocal;
import com.sunwayhorizo.health.business.registries.organization.DepartmentManagerLocal;
import com.sunwayhorizo.health.common.DataTypeUtil;
import com.sunwayhorizo.health.common.DateUtil;
import com.sunwayhorizo.health.common.ListUtil;
import com.sunwayhorizo.health.common.StrUtil;
import com.sunwayhorizo.health.hl7.common.Hl7Exception;
import com.sunwayhorizo.health.hl7.datatypes.BL;
import com.sunwayhorizo.health.hl7.datatypes.CD;
import com.sunwayhorizo.health.hl7.datatypes.CE;
import com.sunwayhorizo.health.hl7.datatypes.CS;
import com.sunwayhorizo.health.hl7.datatypes.ED;
import com.sunwayhorizo.health.hl7.datatypes.ST;
import com.sunwayhorizo.health.hl7.rim.ActParticipation;
import com.sunwayhorizo.health.hl7.rim.ControlAct;
import com.sunwayhorizo.health.hl7.rim.Document;
import com.sunwayhorizo.health.hl7.rim.Organization;
import com.sunwayhorizo.health.hl7.rim.Role;
import com.sunwayhorizo.health.hl7.vocabulary.ActCode;
import com.sunwayhorizo.health.hl7.vocabulary.ActMood;
import com.sunwayhorizo.health.hl7.vocabulary.ParticipationType;
import com.sunwayhorizo.health.hl7.vocabulary.RoleCode;

/**
 * @ClassName TemplateManage <br>
 * @PackageName com.sunwayhorizo.health.business.clinic.emr.template <br>
 * @Description 模板管理 <br>
 * @Author jinzw <br>
 * @Date 2011-03-02 <br>
 * @Version 1.0 <br>
 * @ModifiedDesc <br>
 * @ModifiedDate <br>
 * @ModifiedBy <br>
 * @Copyright 2010-2020 北京三维海容 All Rights Reserved. <br>
 */

@Name("TemplateManager")
@Stateless
public class TemplateManager extends BaseManager implements TemplateManagerLocal
{

    private TemplateQueryLocal templateQuery = (TemplateQueryLocal) Component.getInstance("TemplateQuery");


    public ResultsDTO newTemplate(TemplateDTO template) throws Hl7Exception
    {
        if (null == template)
        {
            log.info("新增模板失败，模板数据template为null");
            return getResultsDTO("新增模板失败", true, null);
        }
        // 创建模板动作
        CE ce = DataTypeUtil.getCE(ActCode.TEMPFILE.code().stringValue());
        Document document = createDocument(ce);
        // 给模板动作赋值
        document = converTemDtoToDoc(document, template);
        // 得到参与模板的所有角色
        Map<CS, Role> socopeMap = findScopeRole(template);
        if (!socopeMap.isEmpty())
        {
            Set<CS> set = socopeMap.keySet();
            for (Iterator<CS> it = set.iterator(); it.hasNext();)
            {
                CS typeCode = it.next();
                Role scopeRole = socopeMap.get(typeCode);
                ActParticipation part = getActFactory().newActParticipation();
                part.setTypeCode(typeCode);
                addParticipation(scopeRole, part);
            }
        }

        ControlAct control = newControlAct(document);
        em.persist(control);

        log.info("新增模板成功" + document.getActId());
        return this.getResultsDTO("新增模板成功", true, document.getActId().toString());
    }


    @SuppressWarnings("rawtypes")
    @Transactional
    public ResultsDTO delTemplate(List templateIds) throws Hl7Exception
    {
        if (ListUtil.isEmpty(templateIds))
        {
            log.info("删除模板文件失败，templateIds为空");
            return getResultsDTO("删除模板文件失败，templateIds为空", false, null);
        }
        String templateId = (String) templateIds.get(0);
        Document document = baseQuery.findDocumentById(templateId);
        if (null == document)
        {
            log.info("删除模板文件失败，没有找到模板");
            return getResultsDTO("删除模板文件失败，没有找到模板", false, null);
        }
        /**
         * 目前状态只用到0、1、2、3
         * 
         * 模板状态 0 未提交 1 提交待审核 2 审核通过 3 审核未通过 4 申请修改 5 申请修改通过 6 申请修改未通过 7 申请删除 8
         * 申请删除通过 9 申请删除未通过
         */
        String state = document.getStatusCode().code().stringValue();
        if (!"2".equals(state))
        {
            // 只有未提交的，申请删除通过,申请修改通过的模板才能被删除-》改为：改为：只有审核的通过的不能删除
            em.remove(document);
        }
        else
        {
            log.info("该模板不能被删除，templateId  " + templateId + "  state  " + state);
            return getResultsDTO("该模板不能被删除", false, null);
        }
        log.info("删除模板文件成功，templateId  " + templateId + "  state  " + state);
        return getResultsDTO("删除模板文件成功", true, null);
    }


    public ResultsDTO updateTemplateFile(TemplateDTO template) throws Hl7Exception
    {
        if (null == template)
        {
            log.info("更新模板文件失败，template为null");
            return getResultsDTO("更新模板文件失败", false, null);
        }
        // 根据模板动作id拿到模板动作
        Document doc = baseQuery.findDocumentById(template.getId());
        // 设置模板动作需要修改的值
        doc = converTemDtoToDoc(doc, template);
        // 修改模板所属范围
        modifyTempleteScope(doc, template);
        em.merge(doc);
        log.info("更新模板文件成功：Id " + template.getId());
        return getResultsDTO("更新模板分类成功", true, null);
    }


    public ResultsDTO findTemplateListByName(String fileName) throws Hl7Exception
    {
        if (StrUtil.isEmpty(fileName))
            return getResultsDTO("文件名称为空", true, null);
        List<Long> list = templateQuery.findDocIdByDocName(fileName);
        if (ListUtil.isNotEmpty(list))
        {
            for (Long entityId : list)
            {
                return findTemplateFile(String.valueOf(entityId));
            }
        }
        return this.getResultsDTO("没有找到关键字对应的值", true, null);
    }


    public ResultsDTO findTemplateListByClassCode(String classCode) throws Hl7Exception
    {
        Long entityId = templateQuery.findTemplateListByClassCode(classCode);
        List<Long> list = templateQuery.findTemplateClassIdByFatherId(String.valueOf(entityId));
        if (ListUtil.isNotEmpty(list))
        {
            return findTemplateList(list);
        }
        else
        {
            return findTemplateList(String.valueOf(entityId));
        }
    }


    public ResultsDTO findCustomizeTemplateList(String calssCode, String empId) throws Hl7Exception
    {
        Long entityId = templateQuery.findTemplateListByClassCode(calssCode);
        List<Object> docs = templateQuery.findCustomizeTempListByEmpId(empId, entityId);
        List<TemplateDTO> result = converTemplateDTOList(docs);
        log.info("获取模板文件列表成功");
        return getResultsDTO("获取自定义模板文件列表成功", true, result);
    }


    public ResultsDTO findTemplateList(List<Long> classIds) throws Hl7Exception
    {
        if (ListUtil.isEmpty(classIds))
            return getResultsDTO("模板分类实体id集合为空", true, null);
        List<Object> docs = templateQuery.findTemplateListByClassIds(classIds);
        if (ListUtil.isEmpty(docs))
        {
            log.info("获取模板文件列表失败：template: ");
            return getResultsDTO("获取模板文件列表失败", true, null);
        }
        List<TemplateDTO> result = converTemplateDTOList(docs);
        log.info("获取模板文件列表成功");
        return getResultsDTO("获取模板文件列表成功", true, result);
    }


    public ResultsDTO findTemplateListByDeptId(String classId, String deptId, String roleType) throws Hl7Exception
    {
        if (null == classId)
            return getResultsDTO("模板分类id为空，不能加载模板 ", true, null);
        List<Object> docs = templateQuery.findAllHospitalTempleteByEntityId(classId, roleType);
        List<TemplateDTO> result = converTemplateDTOList(docs);
        List<TemplateDTO> deptTemplateList = null;
        if (StrUtil.isNotEmpty(deptId))
        {
            List<Object> deptTemplates = templateQuery.finddeptTempleteByEntityId(classId, deptId);
            deptTemplateList = converTemplateDTOList(deptTemplates);
        }
        if (ListUtil.isNotEmpty(deptTemplateList))
        {
            for (TemplateDTO dto : deptTemplateList)
            {
                result.add(dto);
            }
        }
        log.info("获取模板文件列表成功：template: " + classId);
        return getResultsDTO("获取模板文件列表成功：template: " + classId, true, result);
    }


    public ResultsDTO findTemplateListByClassIdDeptIdWGIdsRoleType(String classId, String deptId, List<String> workGroupIds, String roleType)
        throws Hl7Exception
    {
        if (null == classId)
            return getResultsDTO("模板分类id为空，不能加载模板 ", true, null);
        List<Object> docs = templateQuery.findAllHospitalTempleteByEntityId(classId, roleType);
        List<TemplateDTO> result = converTemplateDTOList(docs);
        List<TemplateDTO> deptAndWorkGroupTemplateList = new ArrayList<TemplateDTO>();

        if (StrUtil.isNotEmpty(deptId) || ListUtil.isNotEmpty(workGroupIds))
        {
            List<Object> deptAndWorkGroupTemplates = templateQuery.findTemplateListByEntityIdDeptIdWGIds(classId, deptId, workGroupIds);
            deptAndWorkGroupTemplateList = converTemplateDTOList(deptAndWorkGroupTemplates);
        }
        if (ListUtil.isNotEmpty(deptAndWorkGroupTemplateList))
        {
            for (TemplateDTO dto : deptAndWorkGroupTemplateList)
            {
                result.add(dto);
            }
        }
        Collections.sort(result, new Comparator<TemplateDTO>() {
            @Override
            public int compare(TemplateDTO o1, TemplateDTO o2)
            {
                return o1.getCreationDate().compareTo(o2.getCreationDate());
            }

        });
        log.info("获取模板文件列表成功：template: " + classId);
        return getResultsDTO("获取模板文件列表成功", true, result);
    }


    public ResultsDTO findTemplateList(String classId) throws Hl7Exception
    {
        if (null == classId)
            return null;
        List<Object> docs = templateQuery.findTemplateListByClassTempId(classId);
        if (ListUtil.isEmpty(docs))
        {
            log.info("获取模板文件列表失败：template: " + classId);
            return getResultsDTO("获取模板文件列表失败", true, null);
        }
        List<TemplateDTO> result = converTemplateDTOList(docs);
        log.info("获取模板文件列表成功：template: " + classId);
        return getResultsDTO("获取模板文件列表成功", true, result);
    }


    public ResultsDTO findTemplateFile(String templateId) throws Hl7Exception
    {
        if (StrUtil.isEmpty(templateId))
        {
            log.info("获取模板文件失败，templateId为空");
            return getResultsDTO("获取模板文件失败", true, null);
        }
        Document doc = baseQuery.findDocumentById(templateId);
        TemplateDTO result = convertDocToTemDTO(doc);
        doc = null;
        if (null == result)
        {
            log.info("获取模板文件失败，templateId为空");
            return getResultsDTO("获取模板文件为空", true, null);
        }
        convertTemplateScopeToTempDoc(templateId, result);
        log.info("获取模板文件成功，templateId  " + templateId);
        return getResultsDTO("获取模板文件成功", true, result);
    }


    public void convertTemplateScopeToTempDoc(String actId, TemplateDTO td) throws Hl7Exception
    {
        List<ActParticipation> parts = baseQuery.findPrtcptnsByActId(Long.valueOf(actId));
        for (ActParticipation pat : parts)
        {
            if (pat.getTypeCode().equals(ParticipationType.AUTHEN))
            {
                ED ed = pat.getSignatureText();
                if (null != ed)
                {
                    // 模板打回信息
                    td.setNotPassInfo(ed.stringValue());
                }
            }

            // 参与到模板中作的角色
            Role role = (Role) pat.getRoleparticipation();
            if (role != null)
            {
                CD status = (role != null ? role.getCode() : null);
                if (pat.getTypecode().equals(ParticipationType.TEMPBELORG) || pat.getTypecode().equals(ParticipationType.TEMPBELDEPT)
                        || pat.getTypecode().equals(ParticipationType.TEMPBELWG))
                {
                    // 模板为全院模板
                    if (pat.getTypecode().equals(ParticipationType.TEMPBELORG))
                    {
                        td.setBelongType(ActCode.HOSPITAL.code().toString());
                        td.setOrgRoleId((role != null ? role.getRoleId().toString() : null));
                        td.setScopeName("全院");
                    }
                    // 模板为科室模板
                    if (pat.getTypecode().equals(ParticipationType.TEMPBELDEPT) || pat.getTypecode().equals(ParticipationType.TEMPBELWG))
                    {
                        if (!status.isNull().booleanValue())
                        {
                            String stat = status.code().stringValue();
                            if ((RoleCode.DEPARTMENT.toString()).equals(stat) || (RoleCode.WORKGROUP.toString()).equals(stat))
                            {
                                DepartmentManagerLocal departmentManager = (DepartmentManagerLocal) Component.getInstance("DepartmentManager");
                                Role deptRole = baseQuery.findRoleById(Long.parseLong(role.getRoleId().toString()));
                                DepartmentDTO departmentDTO = departmentManager
                                    .convertDepartmentDTO((Organization) deptRole.getPlayerEntities());
                                if (pat.getTypecode().equals(ParticipationType.TEMPBELDEPT))
                                {
                                    td.setBelongType(ActCode.DEPARTMENT.code().toString());
                                }
                                else if (pat.getTypecode().equals(ParticipationType.TEMPBELWG))
                                {
                                    td.setBelongType(ActCode.WORKGROUP.code().toString());
                                }
                                td.setDeptRoleId((role != null ? role.getRoleId().toString() : null));
                                td.setScopeName(departmentDTO.getDepartmentName());
                            }
                        }
                    }
                }
            }

        }
    }


    public List<TemplateDTO> converTemplateDTOList(List<Object> docs) throws Hl7Exception
    {
        List<TemplateDTO> result = new ArrayList<TemplateDTO>(); // 此分类下的所有文件列表
        EmployeeManagerLocal empManager = (EmployeeManagerLocal) Component.getInstance("EmployeeManager");
        for (int i = 0; i < docs.size(); i++)
        {
            Object[] arg = (Object[]) docs.get(i);
            TemplateDTO td = new TemplateDTO();
            td.setId(arg[0].toString());
            if (null != arg[1])
            {
                td.setName(arg[1].toString());
            }
            if (null != arg[2])
            {
                td.setState(arg[2].toString());
            }
            if (null != arg[3])
            {
                td.setClassId(arg[3].toString());
            }
            if (null != arg[4])
            {
                td.setCreatedBy(arg[4].toString());
                PatientBaseInfoDTO patientBaseInfo1 = empManager.findPlayEntityByRoleId(Long.parseLong(arg[4].toString()));
                if (null != patientBaseInfo1)
                {
                    td.setCreateByName(patientBaseInfo1.getNatureName());
                }
            }
            if (null != arg[5])
            {
                String str = arg[5].toString().substring(0, 19);
                td.setCreationDate(str);
            }
            if (null != arg[6])
            {
                // 是否另页书写
                td.setIsForcePage(arg[6].toString());
            }
            if (null != arg[7])
            {
                // 监控代码
                td.setClassCode(arg[7].toString());
            }

            convertTemplateScopeToTempDoc(arg[0].toString(), td);
            result.add(td);
        }
        return result;
    }


    public Document createDocument(CE ce) throws Hl7Exception
    {
        CS cs = ActMood.EVN; // moodCode
        Document document = this.getActFactory().newDocument(cs, ce, null);
        return document;
    }


    public Document converTemDtoToDoc(Document document, TemplateDTO template) throws Hl7Exception
    {
        // 设置模板名称
        if (!StrUtil.isEmpty(template.getName()))
        {
            ST name = DataTypeUtil.getST(template.getName());
            document.setTitle(name);
        }

        // 设置模板父节点id
        if (!StrUtil.isEmpty(template.getClassId()))
        {
            CE levelCode = DataTypeUtil.getCE(template.getClassId());
            document.setLevelCode(levelCode);
        }
        // 模板质控代码
        if (StrUtil.isNotEmpty(template.getClassCode()))
        {
            CE storageCode = DataTypeUtil.getCE(template.getClassCode());
            document.setStorageCode(storageCode);
        }

        // 模板审核状态
        if (!StrUtil.isEmpty(template.getState()))
        {
            CS statusCode = DataTypeUtil.getCS(template.getState());
            document.setStatusCode(statusCode);
        }

        // 模板内容
        if (null != template.getContents())
        {
            // 如果内容不为空
            ED desc = DataTypeUtil.getED("", template.getContents());
            document.setText(desc);
        }

        // 是否另页书写,0 不需要 1 需要
        if (!StrUtil.isEmpty(template.getIsForcePage()))
        {
            boolean bool = false;
            if ("0".equals(template.getIsForcePage()))
            {
                bool = false;
            }
            else if ("1".equals(template.getIsForcePage()))
            {
                bool = true;
            }
            BL bl = getDataTypeFactory().newBL(bool);
            document.setNegationInd(bl);
        }

        // 创建人
        if (!StrUtil.isEmpty(template.getCreatedBy()))
        {
            document.setCreatedBy(Long.parseLong(template.getCreatedBy()));
            document.setCreationDate(DateUtil.getTimestamp(DateUtil.GetDateTime()));
        }
        // 最后修改人
        if (!StrUtil.isEmpty(template.getLastUpdateBy()))
        {
            document.setLastUpdatedBy(Long.parseLong(template.getLastUpdateBy()));
            document.setLastUpdateDate(DateUtil.getTimestamp(DateUtil.GetDateTime()));
        }
        return document;
    }


    public TemplateDTO convertDocToTemDTO(Document document) throws Hl7Exception
    {
        if (null == document)
            return null;
        TemplateDTO temp = new TemplateDTO();
        if (null != document.getActId())
            temp.setId(document.getActId().toString()); // 模板Id
        CE levelCode = document.getLevelCode();
        if (null != levelCode)
        {
            temp.setClassId(levelCode.code().stringValue()); // 模板分类id
        }
        if (null != document.getTitle())
            temp.setName(document.getTitle().stringValue());// 模板名称

        ED text = document.getText();
        if (null != text && text.isNull().isFalse())
        {
            temp.setContents(text.integrityCheck().byteArray()); // 模板内容
            temp.setComments(text.stringValue()); // 模板描述，说明
        }

        if (null != document.getStatusCode())
            temp.setState(document.getStatusCode().code().stringValue()); // 审核状态

        // 是否另页书写,0 不需要 1需要
        BL bl = document.getNegationInd();
        if (null != bl)
        {
            if (bl.isTrue())
            {
                temp.setIsForcePage("1");
            }
            else
            {
                temp.setIsForcePage("0");
            }

        }
        temp.setCreatedBy(document.getCreatedBy().toString()); // 创建人
        temp.setCreationDate(DateUtil.getFormatTimestamp(document.getCreationDate(), "yyyy-mm-dd hh:mm:ss")); // 创建时间
        temp.setLastUpdateBy(document.getLastUpdatedBy().toString()); // 最后修改人
        temp.setLastUpdateDate(DateUtil.getFormatTimestamp(document.getLastUpdateDate(), "yyyy-mm-dd hh:mm:ss")); // 最后修改时间

        return temp;
    }


    private void modifyTempleteScope(Document doc, TemplateDTO template) throws Hl7Exception
    {
        List<ActParticipation> parts = doc.getParticipations();
        if (ListUtil.isNotEmpty(parts))
        {
            for (int i = 0; i < parts.size(); i++)
            {
                ActParticipation pat = (ActParticipation) parts.get(i);
                Role belongRole = null;
                if (pat.getTypecode().equals(ParticipationType.TEMPBELORG) || pat.getTypecode().equals(ParticipationType.TEMPBELDEPT)
                        || pat.getTypecode().equals(ParticipationType.TEMPBELWG) || pat.getTypecode().equals(ParticipationType.TEMPBELPSN))
                {
                    // 用belongType接收到参与该模板动作的角色到底是全院的还是科室、工作组的个人的
                    String belongType = "";
                    if (pat.getTypecode().equals(ParticipationType.TEMPBELORG))
                    {
                        belongType = ActCode.HOSPITAL.code().toString();
                    }
                    if (pat.getTypecode().equals(ParticipationType.TEMPBELDEPT))
                    {
                        belongType = ActCode.DEPARTMENT.code().toString();
                    }
                    if (pat.getTypecode().equals(ParticipationType.TEMPBELWG))
                    {
                        belongType = ActCode.WORKGROUP.code().toString();
                    }
                    if (pat.getTypecode().equals(ParticipationType.TEMPBELPSN))
                    {
                        belongType = ActCode.PSN.code().toString();
                    }

                    // 模板所属范围与原纪录不一致，需要修改
                    if (!belongType.equals(template.getBelongType()))
                    {

                        if ((ActCode.HOSPITAL.code().toString()).equals(template.getBelongType()))
                        {
                            if (StrUtil.isNotEmpty(template.getOrgRoleId()))
                            {
                                // 全院角色
                                belongRole = baseQuery.findRoleById(Long.parseLong(template.getOrgRoleId()));
                                pat.setRoleparticipation(belongRole);
                                pat.setTypeCode(ParticipationType.TEMPBELORG);
                            }
                            else
                            {
                                log.info("修改模板所属范围失败，全院角色id为空（机构id）");
                            }
                        }
                        else if ((ActCode.DEPARTMENT.code().toString()).equals(template.getBelongType())
                                || (ActCode.WORKGROUP.code().toString()).equals(template.getBelongType()))
                        {
                            if (StrUtil.isNotEmpty(template.getBelDeptRoleId()))
                            {
                                // 科室/病区角色
                                belongRole = baseQuery.findRoleById(Long.parseLong(template.getBelDeptRoleId()));
                                if (template.getBelongType().equals(ActCode.DEPARTMENT.code().toString()))
                                {
                                    pat.setTypeCode(ParticipationType.TEMPBELDEPT);
                                }
                                if (template.getBelongType().equals(ActCode.WORKGROUP.code().toString()))
                                {
                                    pat.setTypeCode(ParticipationType.TEMPBELWG);
                                }
                                pat.setRoleparticipation(belongRole);
                            }
                            else
                            {
                                log.info("修改模板所属范围失败，部门角色id为空");
                            }
                        }
                        else if ((ActCode.PSN.code().toString()).equals(template.getBelongType()))
                        {
                            if (StrUtil.isNotEmpty(template.getEmpRoleId()))
                            {
                                belongRole = baseQuery.findRoleById(Long.parseLong(template.getEmpRoleId()));
                                pat.setTypeCode(ParticipationType.TEMPBELPSN);
                                pat.setRoleparticipation(belongRole);
                            }
                            else
                            {
                                log.info("修改模板所属范围失败，员工角色id 为空");
                            }
                        }
                    }
                    else
                    {
                        // 科室范围之间模板文件的修改
                        if (((ActCode.DEPARTMENT.code().toString()).equals(template.getBelongType()) || (ActCode.WORKGROUP.code().toString())
                            .equals(template.getBelongType())))
                        {
                            if (StrUtil.isNotEmpty(template.getBelDeptRoleId()))
                            {
                                belongRole = baseQuery.findRoleById(Long.parseLong(template.getBelDeptRoleId()));
                                if (template.getBelongType().equals(ActCode.DEPARTMENT.code().toString()))
                                {
                                    pat.setTypeCode(ParticipationType.TEMPBELDEPT);
                                }
                                if (template.getBelongType().equals(ActCode.WORKGROUP.code().toString()))
                                {
                                    pat.setTypeCode(ParticipationType.TEMPBELWG);
                                }
                                pat.setRoleparticipation(belongRole);
                            }
                            else
                            {
                                log.info("修改模板所属范围失败，部门角色id为空");
                            }
                        }
                    }
                }
            }
        }
    }


    private Map<CS, Role> findScopeRole(TemplateDTO template) throws Hl7Exception
    {
        // 文档所属角色
        Role belongRole = null;
        Map<CS, Role> scopeMap = new HashMap<CS, Role>();
        // BelongType判断模板所属范围(PSN 为人员 DEPARTMENT为科室 WORKGROUP为工作组 HOSPITAL为组织 ）
        if (StrUtil.isNotEmpty(template.getBelongType()))
        {
            if (ActCode.HOSPITAL.code().toString().equals(template.getBelongType()))
            {
                if (StrUtil.isNotEmpty(template.getOrgRoleId()))
                {
                    belongRole = baseQuery.findRoleById(Long.parseLong(template.getOrgRoleId()));
                    scopeMap.put(ParticipationType.TEMPBELORG, belongRole);
                }
                else
                {
                    log.info("新增模板失败，全院角色id为空（机构id）");
                }
            }
            else if ((ActCode.DEPARTMENT.code().toString()).equals(template.getBelongType())
                    || (ActCode.WORKGROUP.code().toString()).equals(template.getBelongType()))
            {
                if (StrUtil.isNotEmpty(template.getBelDeptRoleId()))
                {
                    belongRole = baseQuery.findRoleById(Long.parseLong(template.getBelDeptRoleId()));
                    if (template.getBelongType().equals("DEPARTMENT"))
                    {
                        scopeMap.put(ParticipationType.TEMPBELDEPT, belongRole);
                    }
                    if (template.getBelongType().equals("WORKGROUP"))
                    {
                        scopeMap.put(ParticipationType.TEMPBELWG, belongRole);
                    }
                }
                else
                {
                    log.info("新增模板失败，部门角色id为空");
                }
            }
            else if ((ActCode.PSN.code().toString()).equals(template.getBelongType()))
            {
                if (StrUtil.isNotEmpty(template.getEmpRoleId()))
                {
                    belongRole = baseQuery.findRoleById(Long.parseLong(template.getEmpRoleId()));
                    scopeMap.put(ParticipationType.TEMPBELPSN, belongRole);
                }
                else
                {
                    log.info("新增模板失败，员工角色id 为空");
                }
            }
        }
        // 根据分类RIM 实体ID查询模板分类RIM 角色
        if (StrUtil.isNotEmpty(template.getClassId()))
        {
            Role tempClassRole = templateQuery.findClassRoleByEntId(template.getClassId());
            scopeMap.put(ParticipationType.SBJ, tempClassRole);
        }
        // 得到模板制作角色
        if (StrUtil.isNotEmpty(template.getCreatedBy()))
        {
            Role authorRole = baseQuery.findRoleById(Long.parseLong(template.getCreatedBy()));
            scopeMap.put(ParticipationType.AUT, authorRole);
        }
        return scopeMap;

    }

}
